<template>
  <!-- 广告漏出维护 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      :list="topFilterInit"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :isSelectColumn="isSelectColumn"
      :onRowSelectChange="selectChangeHandle"
      :params="flterValue"
      :datakey="'records'"
      :onColumnsChange="(columns) => (this.columns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="importHandle">导入</el-button>
        <el-button size="small" type="primary" @click="exportHandle">导出</el-button>
        <el-button size="small" type="primary" @click="ause">启用</el-button>
        <el-button size="small" type="primary" @click="suse">停用</el-button>
      </template>
    </FilterTable>
    <BaseDialog
      :visible.sync="visibleJXS"
      title="选择经销商"
      width="70%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <TopFilter
        :list="topFilterListJXS"
        :cols="3"
        labelWidth="100"
        @filterChange="changeHandleJXS"
        @onCollapse="collapseHandle"
      ></TopFilter>
      <div class="DepartmentWrap clearfix" v-if="this.visibleJXS">
        <!-- 左侧树 -->
        <div class="leftTree">
          <span :class="sanjiao"></span>
          <el-tree :data="dataTree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
        <!-- 右侧内容 -->
        <div class="rightContent">
          <FilterTable
            ref="tableJXS"
            :columns="columnsJXS"
            :dataSource="dataSource"
            height="auto"
            :onRowSelectChange="onRowSelectChange"
            :onColumnsChange="columns => this.columns = columns"
          >
            <!-- <template slot="controls" slot-scope="props">
                <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle(props)">新增</el-button>
            </template>-->
          </FilterTable>
        </div>
      </div>
      <div style="text-align: center;margin-top: 20px;">
        <el-button size="small" type="primary" @click="confirmJSX">确定</el-button>
        <el-button size="small" type="primary" @click="cancle">关闭</el-button>
      </div>
    </BaseDialog>
    <Drawer
      :visible.sync="visible"
      title="广告露出信息"
      :width="920"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <info v-model="initData" :initData="initData" @close="adialogClose" />
    </Drawer>
    <BaseDialog
      :visible.sync="UploadFileIsShow"
      title="导入"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <importFile
        title="导入"
        actionUrl="/api/cluecenter/adExposed/importAdExposed"
        @close="closeImportHandler"
      />
    </BaseDialog>
    <Drawer
      :visible.sync="visiblehistory"
      title="更改历史"
      :width="920"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <infohistory v-model="initData" :initData="initData" @close="dialogClose" />
    </Drawer>
    <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <dealer-madal ref="addDialogRef" @close="closeDealer" />
    </BaseDialog>
  </div>
</template>
<script>
import dealerMadal from '../../../customerManage/clue/areaBossPush/dealerMadal';
import { getAdExposed, exportAdExposed, upDatetAdExposedStatus } from '@/api/cms-common/adexposed';
import { findFinanceCompany } from '@/api/cms-api/origin/originInfo/OEM';
import { exportExcelFile } from '@/utils/index';
import { getSeries, getModelAll, findFinanceCompanySeriesList } from '@/api/cms-common/basedata';
import info from './info';
import infohistory from './infohistory';
import { queryClueSourceList, getCompanyOrgIsMerge, getOrgType, getDealerArea, getOrgTypeForMin } from '@/api/potenCus/customer/potenCusManage';
import { region } from '@/api/cms-common/region'; //行政区域

// import addDialog from './addDialog';
import { dictionary } from '@/utils/dictMixin';
export default {
  components: {
    info,
    infohistory,
    dealerMadal
  },
  mixins: [dictionary, region],
  data() {
    return {
      visible: false,
      visiblehistory: false,
      visibleDealer: false,
      selectedRows: [], //选中列表中的行
      visibleJXS: false,
      defaultProps: {
        children: 'children',
        label: 'text'
      },
      dataSource: [],
      dataTree: [],
      dataSourceList: '',
      topFilterListJXS: this.createTopFiltersJXS(),
      isSelectColumn: true,
      columnsJXS: this.createTableColumnsJXS(),
      params: {
        orgId: 0,
        type: 10041002
      },
      UploadFileIsShow: false,
      initData: {},
      fetchApi: getAdExposed,
      flterValue: {}, //参数
      sanjiao: 'sanjiao',
      columns: this.creatHeader(),
      fetchParams: null, //ipa 接口
      topFilterInit: this.topFilterInitFun()
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    //初始化字典
    this.initDic();
  },
  methods: {
    //关闭
    cancle() {
      this.visibleJXS = false;
      this.params.orgId = 0;
      this.params.type = 10041002;
    },
    //确定
    confirmJSX() {
      console.log(this.dataSourceList, 'this.dataSourceList');
      this.topFilterInit.find(item => item.fieldName == 'ownerCodes').initialValue = '';
      if (this.dataSourceList) {
        this.topFilterInit.find(item => item.fieldName == 'ownerCodes').initialValue = this.dataSourceList;
        this.visibleJXS = false;
        this.params.orgId = 0;
        this.params.type = 10041002;
      } else {
        this.$message({
          type: 'info',
          message: '请选择一条数据'
        });
      }
    },
    //表格数据变化时
    onRowSelectChange(row) {
      console.log(row, 'val');
      if (row && row.length == 1) {
        row.map(x => {
          this.dataSourceList = x.dealerCode;
        });
      } else {
        this.dataSourceList = '';
        row.map(x => {
          this.dataSourceList += x.dealerCode + ',';
        });
      }
    },
    createTableColumnsJXS() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          filterType: 'input',
          filterItems: [],
          editable: false
          // editType: 'select',
          // editItems: this.createDictList('7021')
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          filterType: 'input',
          filterItems: [],
          editable: false
          // editType: 'select',
          // editItems: []
        }
      ];
    },
    //树节点
    handleNodeClick(data) {
      this.sanjiao = '';
      console.log(data, 'data');
      if (data != '' || data != 'undefined') {
        this.params.orgId = data.value;
        if (data.orgType && data.orgType == '15061005') {
          getOrgTypeForMin(data.value, 15061007).then(res => {
            console.log(res, '小区15061007');
            data.children = res.data;
          });
        } else if (data.orgType && data.orgType == '15061014') {
          getOrgTypeForMin(data.value, 15061015).then(res => {
            console.log(res, '小区15061015');
            data.children = res.data;
          });
        } else {
          getDealerArea(data.value, '', '').then(res => {
            console.log('根据事业部查询经销商', res);
            if (res.resultCode === 200) {
              this.dataSource = res.data.map((x, k) => ({ index: k, dealerCode: x.dealerCode, dealerName: x.dealerName }));
            }
          });
        }
      }
    },
    createTopFiltersJXS() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        }
      ];
    },
    //选择进销商
    changeHandleJXS(val) {
      console.log('123', val);
      getDealerArea('', val.dealerCode ? val.dealerCode : '', val.dealerName ? val.dealerName : '').then(res => {
        console.log('根据事业部查询经销商', res);
        this.dataSource = [];
        if (res.resultCode === 200) {
          this.dataSource = res.data.map((x, k) => ({ index: k, dealerCode: x.dealerCode, dealerName: x.dealerName }));
        }
      });
    },
    // 导出
    async exportHandle(row) {
      // console.log('选择行', this.selectedRows);
      let params = JSON.parse(JSON.stringify(this.flterValue));
      await exportAdExposed(params)
        .then(response => {
          console.log(response.data, '123456765423456yu');
          // console.log(response.data.size, 'response.data.size');
          // console.log(response, 'response');
          // if (response.data.size == 0) {
          //   this.$message({
          //     type: 'info',
          //     message: '数据量超过30000，请选装合适的时间段进行查询'
          //   });
          // } else {
          exportExcelFile(response.data, '广告露出');
          // }
        })
        .catch(err => {
          console.log(err);
        });
    },

    selectChangeHandle(rows) {
      // console.log('rows', rows);
      // if (!rows.length) return;
      this.selectedRows = rows;
      // this.selectedRows.push(rows);
    },
    async ause() {
      if (!this.selectedRows.length) {
        this.$message.info('请先选择数据');
      } else {
        let ids = '';
        this.selectedRows.forEach(item => {
          ids += item.id + ',';
        });
        let params;
        params = { ids: ids, status: 10031001 };
        await upDatetAdExposedStatus(params)
          .then(response => {
            if (true == response.data) {
              this.$message.success('操作成功');
              // 重新加载
              this.flterValue = { ...this.flterValue };
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },

    async suse() {
      console.log('清洗线索', this.selectedRows);
      if (!this.selectedRows.length) {
        this.$message.info('请先选择数据');
      } else {
        let ids = '';
        this.selectedRows.forEach(item => {
          ids += item.id + ',';
        });
        let params;
        params = { ids: ids, status: 10031002 };
        await upDatetAdExposedStatus(params)
          .then(response => {
            if (true == response.data) {
              this.$message.success('操作成功');
              // 重新加载
              this.flterValue = { ...this.flterValue };
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },

    closeImportHandler(val) {
      if (val && val.length > 0) {
        if (val[0].url.errorList && val[0].url.errorList.length > 0) {
        } else {
          this.form.fileList = val[0].url.clue;
        }
        // this.$message.success(val[0].url)
      }

      this.UploadFileIsShow = false;
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'ownerCodes',
          placeholder: '请输入',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-circle-plus" onClick={this.openDriveCancel}></el-button>;
          },
          itemList: []
        },
        // {
        //   type: 'INPUT',
        //   label: '经销商代码',
        //   fieldName: 'ownerCode',
        //   placeholder: '请输入',
        //   initialValue: '',
        //   unitRender: () => {
        //     return <el-button slot="append" icon="el-icon-search" onClick={() => this.dealerHandle()}></el-button>;
        //   }
        // },
        { type: 'SELECT', label: '经销商形式', fieldName: 'financeCompanyId', placeholder: '请输入', initialValue: '', itemList: [] },
        { type: 'SELECT', label: '普通车型', fieldName: 'authorizedModels', placeholder: '请选择', initialValue: '', itemList: [] },
        { type: 'SELECT', label: '特殊车型', fieldName: 'specialAuthorizedModels', placeholder: '请选择', initialValue: '', itemList: [] },
        { type: 'SELECT', label: '是否广告露出', fieldName: 'exposed', placeholder: '请选择', initialValue: '', itemList: [] },
        { type: 'INPUT', label: '修改人', fieldName: 'updatedBy', placeholder: '请输入', initialValue: '' }
      ];
    },
    async initDic() {
      //经销商形式 字典
      this.financeCompanyDic = [];
      let res = await findFinanceCompany({});
      if (res.resultCode === 200) {
        res.data.forEach(x => {
          this.financeCompanyDic.push({ value: x.financeCompanyId, text: x.financeCompanyName });
        });
      }
      //车型 字典
      this.authorizedModelDic = [];
      let ModelRes = await getModelAll();
      if (ModelRes.resultCode == 200) {
        ModelRes.data.forEach(x => {
          this.authorizedModelDic.push({ value: x.modelId, text: x.modelName });
        });
      }
      //是否广告露出 字典
      this.exposedDic = this.createDictList('1004');
      this.topFilterInit.forEach(x => {
        if (x.fieldName == 'financeCompanyId') x.itemList = this.financeCompanyDic;
        else if (x.fieldName == 'authorizedModels' || x.fieldName == 'specialAuthorizedModels') x.itemList = this.authorizedModelDic;
        else if (x.fieldName == 'exposed') x.itemList = this.exposedDic;
      });
    },
    //搜索获取数据
    changeHandle(val) {
      console.log(val, '23456787432123456');
      this.flterValue = Object.assign({}, val);
      //console.log(val);
    },
    // 导入
    importHandle() {
      this.handleType = 'import';
      this.UploadFileIsShow = true;
      //this.form.fileList = [];
    },
    //经销商
    openDriveCancel() {
      this.visibleJXS = true;
      this.topFilterInit.find(item => item.fieldName == 'ownerCodes').initialValue = '';
      this.dataSourceList = '';
      this.getVueTree();
    },
    async getVueTree() {
      this.dataTree = [];
      // 当前经销商有无小区 是否合并
      const res = await getCompanyOrgIsMerge();
      console.log('是否合并', res);
      // isDisArea： 10041001 只有大区   10041002 ：有小区
      // isMerge ：10041001 销售售后合并  10041002 ：不合并
      let { isDisArea, isMerge } = res.data;
      // 1. 不合并只大区 传15061005
      if (isDisArea == 10041001 && isMerge == 10041002) {
        // 查询经销商代码
        const res1 = await getOrgType(15061005);
        console.log('经销商代码1', res1.data);
        if (res1.resultCode == 200) {
          this.dataTree = res1.data.map(x => ({ value: x.orgId, text: x.orgName }));
        }
      }
      // 2. 不合并大小区 传15061005 ,15061007
      if (isDisArea == 10041002 && isMerge == 10041002) {
        let orgType1 = '15061005';
        const res2 = await getOrgType(orgType1);
        console.log('经销商代码2', res2);
        if (res2.resultCode == 200) {
          this.dataTree = res2.data.map(x => ({ value: x.orgId, text: x.orgName, orgType: x.orgType, children: [] }));
        }
      }
      // 3. 合并大区 传15061004
      if (isDisArea == 10041001 && isMerge == 10041001) {
        const res3 = await getOrgType(15061014);
        console.log('经销商代码3', res3);
        if (res3.resultCode == 200) {
          this.dataTree = res3.data.map(x => ({ value: x.orgId, text: x.orgName }));
        }
      }
      // 4. 合并大小区 传15061014， 15061015
      if (isDisArea == 10041002 && isMerge == 10041001) {
        let orgType2 = '15061014';
        const res4 = await getOrgType(orgType2);
        console.log('经销商代码4', res4);
        if (res2.resultCode == 200) {
          this.dataTree = res4.data.map(x => ({ value: x.orgId, text: x.orgName, orgType: x.orgType, children: [] }));
        }
      }
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 130,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.dialogHandle(props.row, 'edit')}>
                  编辑
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.dialogHandleHistory(props.row, 'edit')}>
                  变更历史
                </el-button>
              </div>
            );
          }
        },
        { title: 'ID', dataIndex: 'id', hidden: true, sorter: true },
        { title: 'authorizedModels1', dataIndex: 'authorizedModels1', hidden: true, sorter: true },
        { title: 'authorizedModels2', dataIndex: 'authorizedModels2', hidden: true, sorter: true },
        { title: 'authorizedModels3', dataIndex: 'authorizedModels3', hidden: true, sorter: true },
        { title: 'authorizedModels4', dataIndex: 'authorizedModels4', hidden: true, sorter: true },
        { title: '事业部', dataIndex: 'deptName', sorter: true },
        {
          title: '办事处',
          dataIndex: 'officeName',
          sorter: true
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createRegionText(props.row.provinceName)}</span>;
          }
        },
        { title: '经销商代码', dataIndex: 'ownerCode', sorter: true },
        {
          title: '经销商全称',
          dataIndex: 'dealerName',
          sorter: true
        },
        { title: '经销商形式', dataIndex: 'financeCompanyId', sorter: true },
        { title: '普通授权车型', dataIndex: 'authorizedModels', sorter: true },
        {
          title: '特殊授权车型',
          dataIndex: 'specialAuthorizedModels',
          sorter: true
        },
        {
          title: '是否广告露出',
          dataIndex: 'exposed',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.exposed, 1004)}</span>;
          }
        },
        {
          title: '是否黑名单',
          dataIndex: 'isBlack',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.exposed, 1004)}</span>;
          }
        },
        {
          title: '修改人',
          dataIndex: 'updatedBy',
          sorter: true
        },
        {
          title: '修改时间',
          dataIndex: 'updatedAt',
          dateFormat: 'yyyy-MM-dd HH:mm',
          sorter: true
        }
      ];
    },
    // 广告露出打开窗口 -传数据
    dealerHandle() {
      this.visibleDealer = true;
    },
    // 广告露出关闭窗口 -返回数据
    closeDealer(data) {
      //返回数据逻辑自己写
      this.topFilterInit[5].initialValue = '广告露出';
      this.visibleDealer = data.visible; //关闭弹窗
    },
    //详情
    dialogHandle(row, tpye) {
      this.visible = true;
      this.initData = row;
    },
    //变更历史
    dialogHandleHistory(row, tpye) {
      this.visiblehistory = true;
      this.initData = row;
    },
    //关闭详情
    adialogClose(data) {
      this.visible = false;
      if (data === 'refresh') {
        // 重新加载
        this.flterValue = { ...this.flterValue };
      }
    },
    dialogClose(data) {
      this.visible = false;
      // if (data.type === 'refresh') {
      //   // 重新加载
      //   this.fetchParams = { ...this.fetchParams };
      // }
    },

    collapseHandle() {
      this.$nextTick(() => {
        //this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    }
  }
};
</script>

<style lang="less" scoped>
.DepartmentWrap {
  // height: 79vh;
  height: 26vw;
  border: 1px solid #000;
  box-sizing: border-box;
  overflow: hidden;
  .leftTree {
    width: 36%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    float: left;
    padding: 10px;
    box-sizing: border-box;
    position: relative;
  }

  .rightContent {
    width: 64%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    float: left;
    box-sizing: border-box;
    padding: 10px;
    border-left: 2px solid #eee;
  }
}
.sanjiao {
  position: absolute;
  left: 18px;
  top: 19px;
  z-index: 99;
  width: 0;
  height: 0;
  border-top: 3px solid transparent;
  border-bottom: 5px solid transparent;
  border-left: 9px solid #ccc;
}
</style>
